
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="活动昵称" style="width: 200px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
        <el-select v-model="listQuery.clubId" placeholder="所属社团"   style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in clubs"  :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        条件查询
      </el-button>
      <el-button v-if="role!='admin'" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        发布活动
      </el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button> -->
      <!-- <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 200%;"
      @sort-change="sortChange">
      <el-table-column label="活动编号" prop="id" sortable="custom" align="center" width="80"
        :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动海报" width="150px" align="center">
        <template slot-scope="{ row }">
            <el-image style="width: auto; height: 100px; border:none;cursor: pointer;" 
            :src="getImage(row.logo)" 
            :preview-src-list="[ getImage(row.logo) ]" >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>  
          </el-image>
          </template>
      </el-table-column>
      <el-table-column label="活动名称" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动描述" width="150px" align="center">
        <template slot-scope="{row}">
          <span class="spandev">{{ row.description | stripTags }}</span>
        </template>
      </el-table-column>
      <el-table-column label="限制人数" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nums }}</span>
        </template>
      </el-table-column>
      <el-table-column label="组织人" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.users.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属社团" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.clubs.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ formatDateTime(row.startTime)  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ formatDateTime(row.endTime)  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="参与人数" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.count }}</span>
        </template>
      </el-table-column>
      <el-table-column label="面向用户" width="150px" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.turnUser=='true'" type="success">面向全部用户</el-tag>
            <el-tag v-if="row.turnUser=='false'" type="warning">面向社团成员</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="处理状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
            <el-tag v-if="row.status==1" type="success">审核通过</el-tag>
            <el-tag v-if="row.status==0" type="info">未处理</el-tag>
            <el-tag v-if="row.status==-1"  type="warning">已驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Actions" align="center" width="400" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button v-if="row.status == 1 " type="success" size="mini"  @click=" handleMemberList(row)">
            查看参与人数
          </el-button>
          <el-button v-if="row.status == 1 " type="warning" size="mini"  @click=" handleMail(row)">
            邮件通知
          </el-button>
          <el-button  v-if="row.status == '0' || role=='admin'" type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status == 0 && role=='admin'" type="success" size="mini" @click="handleStatus(row.id,1)">
            通过
          </el-button>
          <el-button v-if="row.status == 0 && role=='admin'" type="error" size="mini" @click="handleStatus(row.id,-1)">
            驳回
          </el-button>
          <el-button v-if="row.status == '0' || role=='admin' " size="mini" type="danger" @click="handleDelete(row, $index)">
            删除 
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px"
        style="width: 500px; margin-left:50px;">
  <el-form-item label="活动名称" prop="name">
    <el-input v-model="temp.name" type="text" :required="true" />
    <el-input v-model="temp.logo" type="text"  :required="true" style="display: none;" />
  </el-form-item>
  <el-form-item label="活动描述" prop="description">
    <quill-editor 
	   class="ql-editor"
	   v-model="temp.description" 
	   ref="myQuillEditor" 
	   :options="editorOption"
     
     >
	</quill-editor>
  </el-form-item>
  <el-form-item label="活动海报">
    <el-upload class="avatar-uploader" :action="getup()" :show-file-list="false"
      :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </el-form-item>
  <el-form-item label="所属社团" prop="departmentId">
    <el-select v-model="temp.clubId" class="filter-item" placeholder="Please select">
      <el-option v-for="item in clubs" :key="item.id" :label="item.name" :value="item.id" />
    </el-select>
  </el-form-item>
  <el-form-item label="人数限制" prop="createdAt">
    <el-input v-model="temp.nums" type="text" :required="true" />
  </el-form-item>
  <el-form-item label="活动开始时间" prop="createdAt">
    <el-date-picker v-model="temp.startTime" type="datetime" placeholder="Please pick a date" />
  </el-form-item>
  <el-form-item label="活动结束时间" prop="createdAt">
    <el-date-picker v-model="temp.endTime" type="datetime" placeholder="Please pick a date" />
  </el-form-item>
  <el-form-item label="是否面向全部用户开放加入" prop="">
    <el-switch
  v-model="temp.turnUser"
  active-color="#13ce66"
  inactive-color="#ff4949"
  active-value="true"
    inactive-value="false"
  >
</el-switch>
  </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-drawer
  title="以下是参与本活动的用户名单"
  :visible.sync="table"
  direction="rtl"
  size="50%">
   <el-table :data="gridData">
      <el-table-column property="createdAt" label="参与时间" width="150"></el-table-column>
      <el-table-column property="members.name" label="参与成员" width="200"></el-table-column>
      <el-table-column property="events.name" label="活动名称"></el-table-column>
    </el-table>
</el-drawer>
  </div>
</template>
<style>
.quill-editor /deep/ .ql-container {
    min-height: 220px;
  }

  .ql-container {
    min-height: 230px;
  }
.ql-toolbar.ql-snow .ql-picker.ql-expanded .ql-picker-options {
  border-color: #ccc;
  height: 125px;
  overflow: auto;
}
.spandev{
    display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; text-overflow: ellipsis;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  .avatar {
    width: 150px;
    height: 150px;
    display: block;
  }
</style>
<script>
import { fetchList, fetchPv, createArticle, updateArticle, deleteArticle, fetchclubsmentList,getUserList,updateStatus,getMemberList,sendMail } from '@/api/events'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { apply } from 'body-parser'
import { quillEditor } from 'vue-quill-editor'
 
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
let logoname='';
const clubs = [
]
const users=[

]
const apply_status= [
  { key: 0, val: '关闭' },
  { key: 1, val: '开启' },
]
export default {
  name: 'ComplexTable',
  components: { Pagination,quillEditor },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },

    stripTags: function(str) {
      return str.replace(/<[^>]+>/g, '');
    }
  },
  data() {
    return {
      imageUrl:'',
      logoname:'',
      table: false,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 10,
        name: undefined,
      },
      
      gridData: [],
      users,
      role:localStorage.getItem("roles"),
      importanceOptions: [1, 2, 3],
      clubs,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      apply_status,
      temp: {
        id: undefined,
        name: undefined,
        departmentId: undefined,
        createdAt: '',
        isApply: undefined,
        logo:'',
        createdBy:'',
        turnUser: false,
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '在线编辑',
        create: '添加活动'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
      //   name: [
      //   { required: true, message: '社团名必须填写', trigger: 'blur' },
      // ],
      // description: [
      //   { required: true, message: '社团描述必须填写', trigger: 'blur' },
      // ],
      // departmentId: [
      //   { required: true, message: '所属部门必须选择', trigger: 'change' },
      // ],
      // createdAt: [
      //   { required: true, message: '建团时间必须填写', trigger: 'change' },
      // ],
      // isApply: [
      //   { required: true, message: '开启入团必须选择', trigger: 'change' },
      // ],
      },
      downloadLoading: false,
      editorOption: {
	        modules: {
		          toolbar: [
		             ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
					 ['blockquote', 'code-block'], // 引用  代码块
					  [{ header: 1 }, { header: 2 }], // 1、2 级标题
					  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
					  [{ script: 'sub' }, { script: 'super' }], // 上标/下标
					  [{ indent: '-1' }, { indent: '+1' }], // 缩进
					  [{ direction: 'rtl' }], // 文本方向
					  [{ size: ['12px', false, '16px', '18px', '20px', '30px'] }], // 字体大小
					  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
					  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
					  [{ font: [false, 'SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial'] }], // 字体种类
					  [{ align: [] }], // 对齐方式
					  ['clean'], // 清除文本格式
					  ['link', 'image', 'video']] // 链接、图片、视频
		        },
		        placeholder: '请输入正文'
	      	} 
    }
  },
  created() {
    this.getList(),
      this.getclubsList(),
      this.getUserList()
  },
  methods: {
    
    getImage (image) {
            return `${process.env.VUE_APP_BASE_URL}/common/download?name=${image}`
          },
    getup(){
        return `${process.env.VUE_APP_BASE_URL}/common/upload`
    },
          formatDateTime(dateTime) {
      const d = new Date(dateTime)
      const year = d.getFullYear()
      const month = ('0' + (d.getMonth() + 1)).slice(-2)
      const day = ('0' + d.getDate()).slice(-2)
      const hour = ('0' + d.getHours()).slice(-2)
      const minute = ('0' + d.getMinutes()).slice(-2)
      return `${year}-${month}-${day} ${hour}:${minute}`
    },
    handleStatus(id,status) {
      updateStatus(id,status).then(() => {
        this.getList();
        this.$notify({
          title: '操作成功',
          message: '操作审核成功！',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      logoname=res.data;
      console.log(logoname);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG && !isPNG) {
          this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
                  return (isJPG || isPNG) && isLt2M;
      },
      getclubsList() {
      fetchclubsmentList().then(response => {
        this.clubs = response.data;
      })
    },
    getUserList() {
      getUserList().then(response => {
        this.users = response.data;
      })
    },
    handleMemberList(row) {
      getMemberList(row).then(response => {
        this.table=true;
        response.data.createdAt=this.formatDateTime(response.data.createdAt);
        // debugger
        this.gridData = response.data;
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total

        // Just to simulate the time of the request
        // setTimeout(() => {
        this.listLoading = false
        // }, 1.5 * 1000)
      })

    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: undefined,
        departmentId: undefined,
        createdAt: '',
        isApply: undefined,
        logo:'',
        turnUser: "",
      } 
    },
    handleCreate() {
      this.resetTemp()
      this.imageUrl='';

      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleMail(row){
      this.$confirm('此操作将批量发布邮件到社团团员的邮箱中, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({
          lock: true,
          text: '批量发送中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        sendMail(row).then(response=>{
          if(response.code==20000){
            this.$message({
            type: 'success',
            message: '发送了('+response.data+')!个邮件'
          });
            loading.close();
          }
        })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '操作取消'
          });          
        });
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.logo = logoname;
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          createArticle(this.temp).then(() => {
            // this.list.unshift(this.temp)
            this.getList();
            this.dialogFormVisible = false
            this.$notify({
              title: '添加成功了',
              message: '添加社团成功！',
              type: 'success',
              duration: 2000
            })
            this.resetTemp()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.logo = row.logo;
      this.imageUrl=this.getImage(row.logo);
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
         
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            // const index = this.list.findIndex(v => v.id === this.temp.id)
            // this.list.splice(index, 1, this.temp)
            this.getList();
            this.dialogFormVisible = false
            this.$notify({
              title: '更新成功',
              message: '恭喜你，更新成功了',
              type: 'success',
              duration: 2000
            })
            this.resetTemp()
          })
        }
      })
    },
    handleDelete(row, index) {
      deleteArticle(row).then(() => {
        this.$notify({
          title: '操作成功',
          message: '删除社团信息成功！',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })

    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
